<template>
    <aside class="left-menu" :style="{width: widthData + 'px'}">
        <div class="user-info" :style="{opacity: opacityData}">
            <div class="user-header">
                <img v-if="roleId == 1" src="./../assets/images/avatar_icon1.png" />
                <img v-else-if="roleId == 2" src="./../assets/images/avatar_icon2.png" />
                <img v-else-if="roleId == 3 || roleId == 4" src="./../assets/images/avatar_icon3.png" />
            </div>
            <div class="user-name">你好！{{ username }}</div>
            <div class="user-list">
                <el-row>
                    <el-col :span="8">
                        <router-link :class="{ notification : notificationActive==true }" to="/student/notification" v-if="roleId == 1" @click.native="notificationActiveFn">
                            <div class="list-img">
                                <img src="./../assets/images/user_info_icon1.png" />
                            </div>
                            <span>消息通知</span>
                        </router-link>
                        <router-link :class="{ notification : notificationActive==true }" to="/teacher/notification" v-else-if="roleId == 2"  @click.native="notificationActiveFn">
                            <div class="list-img">
                                <img src="./../assets/images/user_info_icon1.png" />
                            </div>
                            <span>消息通知</span>
                        </router-link>
                        <router-link :class="{ notification : notificationActive==true }" to="/admin/notification" v-else-if="roleId == 3 || roleId == 4"  @click.native="notificationActiveFn">
                            <div class="list-img">
                                <img src="./../assets/images/user_info_icon1.png" />
                            </div>
                            <span>消息通知</span>
                        </router-link>
                    </el-col>
                    <el-col :span="8">
                        <router-link to="/student/myInfo" v-if="roleId == 1">
                            <div class="list-img">
                                <img src="./../assets/images/user_info_icon2.png" />
                            </div>
                            <span>我的信息</span>
                        </router-link>
                        <router-link to="/teacher/myInfo" v-else-if="roleId == 2">
                            <div class="list-img">
                                <img src="./../assets/images/user_info_icon2.png" />
                            </div>
                            <span>我的信息</span>
                        </router-link>
                        <router-link to="/admin/myInfo" v-else-if="roleId == 3 || roleId == 4">
                            <div class="list-img">
                                <img src="./../assets/images/user_info_icon2.png" />
                            </div>
                            <span>我的信息</span>
                        </router-link>
                    </el-col>
                    <el-col :span="8" @click.native="modifyPassWordFn">
                        <div class="list-img">
                            <img src="./../assets/images/user_info_icon3.png" />
                        </div>
                        <span>修改密码</span>
                    </el-col>
                </el-row>
            </div>
        </div>
        <div class="arrow-btn" @click="arrowFn" :class="{ active: activeData}">
            <img src="./../assets/images/arrow_left_icon.png" />
        </div>
        <el-menu :default-active="activeIndex" class="el-menu-vertical-demo" :style="{opacity: opacityData}" router>
            <template v-for="(issue,index) in $router.options.routes">
                <template v-if="issue.name === $store.state.leftNavState">
                    <template v-for="(item,index) in issue.children">
                          <el-menu-item
                                v-if="!item.leaf"
                                :disabled="!downloadAble && (item.menuName == '案例源码' || item.menuName == '案例文档')"
                                @click="noDownload(item)"
                                :key="item.path"
                                :index="item.path">
                                <span slot="title">{{item.menuName}}</span>
                          </el-menu-item>
                    </template>
              </template>
            </template>
        </el-menu>
        <el-dialog title="修改密码" :visible.sync="dialogFormVisible" width="500px" @close="closeDialog">
            <el-form :model="form" :rules="rules" ref="form" label-width="100px">
                <el-form-item label="原密码 :" prop="oldpassWord" style="width:80%;">
                    <el-input type="password" v-model="form.oldpassWord" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="新密码 :" prop="passWord" style="width:80%;">
                    <el-input type="password" v-model="form.passWord" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="确认密码 :"  prop="checkPass" style="width:80%;">
                    <el-input type="password" v-model="form.checkPass" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align:center;">
                <el-button type="primary" @click="submitForm('form')">保存</el-button>
            </div>
        </el-dialog>
    </aside>
</template>

<script>
	import { mapState } from 'vuex'
	export default {
        name: 'leftMenu',
		data () {
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'))
                } else {
                    if (this.form.checkPass !== '') {
                        this.$refs.form.validateField('checkPass')
                    }
                        callback()
                    }
                }
			var validatePass2 = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请再次输入密码'))
				} else if (value !== this.form.passWord) {
					callback(new Error('两次输入密码不一致!'))
				} else {
					callback()
				}
            }
			return {
                studentActive: '2',
                //websockt地址
                projectAccessUrl: '',
                activeIndex: '',
                widthData: 230,
                opacityData: 1,
                activeData: false,
                dialogFormVisible: false,
                form: {
                    oldpassWord: '',
                    passWord: '',
                    checkPass: ''
                },
                rules: {
                    oldpassWord: [
                        { required: true, message: '请输入原密码', trigger: 'blur' }
					],
                    passWord: [
                        { required: true, message: '请输入新密码', trigger: 'blur' },
						{ required: true, validator: validatePass, trigger: 'blur' }
					],
					checkPass: [
                        { required: true, message: '请确认密码', trigger: 'blur' },
						{ required: true, validator: validatePass2, trigger: 'blur' }
                    ]
                },
                userId: '',
                roleId: '',
                // username: '',
                notificationActive: '',

                // 是否下载源代码
                downloadAble: ''

			}
        },
        computed:{
			...mapState(['itemServiceValue', 'username'])
        },
        created () {
            let self = this
            if (this.$store.state.username == '') {
                    this.$router.replace({
                    path:'/login'
                })
            }
            this.roleId = JSON.parse(window.localStorage.getItem('access-user')).roleId
            this.downloadAble = JSON.parse(window.localStorage.getItem('access-user')).downloadAble
            // this.username = JSON.parse(window.localStorage.getItem('username'))
            this.projectAccessUrl = JSON.parse(window.localStorage.getItem('access-user')).projectAccessUrl
            this.userId = JSON.parse(window.localStorage.getItem('access-user')).id
            this.initWebSocket();
        },
        destroyed: function() {
　　　　    //页面销毁时关闭长连接
　　　　　　this.over()
        },
		mounted () {
            this.activeIndex = this.$route.matched[1].path;
        },
        methods: {
            fetchDate() {
                var cur_path = this.$route.path; //获取当前路由
                // if (this.$store.state.username == '') {
                //      this.$router.replace({
                //         path:'/login'
                //     })
                // }
                this.activeIndex = this.$route.matched[1].path;
            },
            initWebSocket(){ //初始化weosocket
                const wsuri = "ws://"+this.projectAccessUrl+"/dataplatform/sendNoticeChange/"+this.userId;
                this.websock = new WebSocket(wsuri);
                this.websock.onmessage = this.websocketonmessage;
                this.over = () => {
                    this.websock.close()
                }
            },
            websocketonmessage(e){ //数据接收
                const redata = JSON.parse(e.data);
                if(redata.data == 'show'){
                    this.notificationActive = true
                }
            },
            notificationActiveFn(){
                this.notificationActive = false
            },
            //菜单动画
            arrowFn() {
                if(this.widthData == 230){
                    this.widthData = 0
                    this.activeData = true
                    this.opacityData = 0
                }else{
                    this.widthData = 230
                    this.activeData = false
                    this.opacityData = 1
                }
            },
            //关闭弹窗
            closeDialog(){
                this.$refs.form.resetFields()
            },
            //修改密码
            modifyPassWordFn () {
                this.form.oldpassWord = ''
                this.form.passWord = ''
                this.form.checkPass = ''
                this.dialogFormVisible = true
            },
            //修改密码表单提交
            submitForm(formName) {
				this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.$http.post('/dataplatform/system/mana/tsa/modifyPassword', {
                            oldPassword: this.form.oldpassWord,
                            password: this.form.passWord
                        }).then((response) => {
                            let res = response.data
                            if(res.code == '200') {
                                this.$alert('修改成功,点击确定退出登录', '提示', {
                                    confirmButtonText: '确定',
                                    callback: action => {
                                        localStorage.removeItem('access-user')
                                        this.$router.replace('/login'); //用go刷新
                                    }
                                });
                            }else if(res.code == '401'){
                                this.$router.replace({
                                    path:'/login'
                                })
                            }else{
                                this.$message.error(res.message)
                            }
                        })
                    }
                })
            },

            // 禁止下载
            // noDownload(item){
            //     if(!this.downloadAble && (item.menuName == '案例简介' || item.menuName == '案例文档')){
            //         this.$message.error('此功能不能使用')
            //         return
            //     }
            // }
        },
        watch: {
            "$route": "fetchDate",
            username(a,b){
                console.log(a,b)
            }
        }
	}
</script>
